import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import {setDocumentTitle, domTitle} from '@/utils/domUtil'
import {ACCESS_INFO, ACCESS_ROLES, ACCESS_TOKEN} from '@/store/mutation-types'
import {i18nRender} from '@/locales'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const allowList = ['login', 'loginz'] // no redirect allowList
const loginRoutePath = '/auth/login'
const loginRoutePath2 = '/auth/loginz'
const defaultRoutePath = '/'


router.beforeEach(async (to, from, next) => {
    if (to.path === loginRoutePath) {
        sessionStorage.setItem('paths', loginRoutePath)
    }
    if (to.path === loginRoutePath2) {
        sessionStorage.setItem('paths', loginRoutePath2)
    }
    NProgress.start() // start progress bar
    to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`)
    /* has token */
    if (storage.get(ACCESS_TOKEN)) {
        if (to.path === loginRoutePath) {
            
            next({path: defaultRoutePath})
            NProgress.done()
        } else if (to.path === loginRoutePath2) {
            
            next({path: defaultRoutePath})
            NProgress.done()
        } else {
            if (!store.getters.roles || !store.getters.roles.length) {
                await store.dispatch('GetInfo')
                next()
            } else {
                console.log(store.getters.roles, 'store.getters.roles')
                next()
            }
        }
    } else {
        if (allowList.includes(to.name)) {
            // 在免登录名单，直接进入
            next()
        } else {
            next({path: sessionStorage.getItem('paths') || loginRoutePath, query: {redirect: to.fullPath}})
            NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
        }
    }
})

router.afterEach(() => {
    NProgress.done() // finish progress bar
})
